package com.ruoyi.client.service.impl;

import com.ruoyi.client.mapper.ClientUserMapper;
import com.ruoyi.client.pojo.form.UpdatePwdForm;
import com.ruoyi.client.pojo.form.UserLoginForm;
import com.ruoyi.client.pojo.form.UserRegisterForm;
import com.ruoyi.client.pojo.vo.UserVo;
import com.ruoyi.client.service.IClientUserService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;

import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.novel.domain.Users;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ClientUserServiceImpl implements IClientUserService {
    private static final Logger logger = LoggerFactory.getLogger(ClientUserServiceImpl.class);
    
    @Resource
    private ClientUserMapper clientUserMapper;
    
    @Override
    public UserVo login(UserLoginForm form) {
        logger.info("开始处理用户登录请求，表单数据: " + form);
        
//        判断用户是否存在
        Users user=clientUserMapper.selectByName(form.getName());
        if (user==null){
            logger.error("用户不存在，用户名: " + form.getName());
            throw new ServiceException("用户名不存在或密码错误");
        }
        
        logger.info("找到用户，用户ID: " + user.getUserId() + ", 用户名: " + user.getUsername());
        logger.info("用户salt值: " + user.getSalt());
        logger.info("用户passwordHash值: " + user.getPasswordHash());
        
//        密码加密处理
        String passwordMd5= Md5Utils.hash(form.getPassword() + user.getSalt());
        logger.info("输入密码加密后: " + passwordMd5);
        
        if (passwordMd5.equals(user.getPasswordHash())){
            UserVo userVo=new UserVo();
            BeanUtils.copyProperties(user,userVo);
            logger.info("用户登录成功");
            return userVo;
        }
        
        logger.error("密码错误，输入密码加密后: " + passwordMd5 + ", 数据库中密码: " + user.getPasswordHash());
//        抛出异常
        throw new ServiceException("用户登录错误");
    }

    @Override
    public UserVo register(UserRegisterForm form) {
        logger.info("开始处理用户注册，表单数据: " + form);
        logger.info("表单中的头像URL: '" + form.getAvatarUrl() + "'");
        logger.info("表单中头像URL是否为null: " + (form.getAvatarUrl() == null));
        logger.info("表单中头像URL是否为空字符串: '" + form.getAvatarUrl() + "'".equals("''"));
        
        Users user = clientUserMapper.selectByName(form.getUsername());
        if (user != null) {
            throw new ServiceException("用户名已存在");
        }
        user = new Users();
        BeanUtils.copyProperties(form,user);
        
        // 打印用户对象信息
        logger.info("准备注册的用户对象: " + user);
        logger.info("用户对象中的头像URL: '" + user.getAvatarUrl() + "'");
        logger.info("用户对象中头像URL是否为null: " + (user.getAvatarUrl() == null));
        logger.info("用户对象中头像URL是否为空字符串: '" + user.getAvatarUrl() + "'".equals("''"));
        
        // 密码加密处理
        String salt = Md5Utils.hash(String.valueOf(System.currentTimeMillis()));
        String passwordMd5 = Md5Utils.hash(form.getPassword_hash() + salt);
        user.setSalt(salt);
        user.setPasswordHash(passwordMd5);
        
        // 调用数据层,注册用户数据
        logger.info("准备插入数据库的用户对象: " + user);
        logger.info("插入数据库前的头像URL: '" + user.getAvatarUrl() + "'");
        logger.info("插入数据库前头像URL是否为null: " + (user.getAvatarUrl() == null));
        logger.info("插入数据库前头像URL是否为空字符串: '" + user.getAvatarUrl() + "'".equals("''"));
        
        // 检查avatarUrl字段是否满足插入条件
        boolean avatarUrlCondition = user.getAvatarUrl() != null;
        logger.info("avatarUrl插入条件 (user.getAvatarUrl() != null): " + avatarUrlCondition);
        
        if (clientUserMapper.register(user)) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            logger.info("注册成功，返回的用户对象: " + userVo);
            logger.info("返回用户对象中的头像URL: '" + userVo.getAvatarUrl() + "'");
            return userVo;
        }
        return null;
    }

    @Override
    public UserVo selectById(Long id) {
        UserVo userVo = clientUserMapper.selectById(id);
        logger.info("根据ID查询用户，用户ID: " + id + ", 查询结果: " + userVo);
        if (userVo != null) {
            logger.info("查询到的用户头像URL: '" + userVo.getAvatarUrl() + "'");
        }
        return userVo;
    }

//    修改密码
    @Override
    public int updatePwd(UpdatePwdForm form) {
        logger.info("开始处理密码修改请求，表单数据: " + form);
        
        Users user = clientUserMapper.selectByName(form.getName());
        if (user == null) {
            logger.error("用户不存在，用户名: " + form.getName());
            throw new ServiceException("该用户不存在");
        }
        
        logger.info("找到用户，用户ID: " + user.getUserId() + ", 用户名: " + user.getUsername());
        logger.info("用户当前的salt值: " + user.getSalt());
        logger.info("用户当前的passwordHash值: " + user.getPasswordHash());

        Users user0 = new Users();
        // 生成新的salt以提高安全性
        String newSalt = Md5Utils.hash(String.valueOf(System.currentTimeMillis()));
        String passwordNew = form.getPasswordNew();
        String passwordMd5 = Md5Utils.hash(passwordNew + newSalt);
        
        logger.info("新salt值: " + newSalt);
        logger.info("新密码加密后: " + passwordMd5);
        
        // 更新密码和salt
        user0.setPasswordHash(passwordMd5);
        user0.setSalt(newSalt);
        user0.setUserId(user.getUserId());
        
        logger.info("准备更新用户密码和salt，用户ID: " + user0.getUserId());

        int result = clientUserMapper.updatePwd(user0);
        
        logger.info("密码更新结果: " + result);
        
        // 验证更新是否成功
        if (result > 0) {
            // 重新查询用户信息验证密码是否更新
            Users updatedUser = clientUserMapper.selectByName(form.getName());
            if (updatedUser != null) {
                logger.info("更新后的用户salt值: " + updatedUser.getSalt());
                logger.info("更新后的用户passwordHash值: " + updatedUser.getPasswordHash());
            }
        }
        
        return result;
    }
    
    // 更新用户信息
    @Override
    public int updateUserInfo(Users user) {
        return clientUserMapper.updateUserInfo(user);
    }
}